package com.offcn.servlet;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.CourseDetail;
import com.offcn.service.CourseDetailService;
import com.offcn.service.CourseService;
import com.offcn.service.Impl.CourseDetailServiceImpl;
import com.offcn.service.Impl.CourseServiceImpl;
import com.offcn.utils.ResultBean;
import com.offcn.utils.UploadUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/courseDetail")
@MultipartConfig
public class CourseDetailServlet extends BaseServlet {
    ResultBean bean = null;

    protected void addDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        Map<String, String[]> map = request.getParameterMap();
        CourseDetail detail = new CourseDetail();
        BeanUtils.populate(detail, map);
        CourseDetailService service = new CourseDetailServiceImpl();
        int i = service.addDetail(detail);
        if (i > 0) {
            bean = new ResultBean(200, "添加明细成功", i);
        }else {
            bean = new ResultBean(500, "添加明细失败", null);
        }
        response.getWriter().write(JSON.toJSONString(bean));
    }

    //    上传文件
    protected void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        String fileName = UploadUtils.uploadFile(part);
        String tail = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("jpg".equals(tail) || "png".equals(tail)) {
            bean = new ResultBean(1, "图片上传成功", fileName);
        } else if ("mp4".equals(tail)) {
            bean = new ResultBean(3, "视频上传成功", fileName);
        } else {
            bean = new ResultBean(500, "上传失败", null);
        }
        response.getWriter().write(JSON.toJSONString(bean));
    }
    /***************************************用户页面业务*******************************************************/

//    章节查询
    protected void findByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        CourseDetailService service = new CourseDetailServiceImpl();
        List<String> list = service.findByType(cid);
        if (null != list && list.size() > 0) {
            bean = new ResultBean(200,"查询成功",list);
        }else {
            bean = new ResultBean(500, "查询失败", null);
        }
        response.getWriter().write(JSON.toJSONString(bean));
    }
}
